/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 */


(function(){
var version = {
	url : '/index.php?s=/api_version',
	check : function(){
		version.ajax(version.url + '-druson~1', function(data){
			if(D.empty(data) || !$.isArray(data))return;
			version.update(data);
		});
	},	
	update : function(data, index, callback){
		data = $.isArray(data) ? data : [data];
		index = index || 0;
		var id = data[index];
		version.ajax(version.url + '-' + id + '-druson~1', function(data){
			if($.isFunction(callback))callback(data);
			if(D.empty(data) || !data.status || index + 1 >= data.length)return;
			version.update(data, index + 1);
		});
	},
	ajax : function(url, callback){
		$.ajax({
			url : url,
			type : 'GET',
			dataType : "json",
			cache : false,
			success : callback
		});
	}
};

var viewer = {
	event : function(){
		var list_table = $('table.list'), span, elem, panel;
		list_table.find('thead input[type=checkbox]:first').bind('change', function(){list_table.find('tbody>tr>td:first-child>input[type=checkbox]').prop('checked', $(this).is(':checked')) ;});
		list_table.find('tbody>tr:odd').addClass('odd');
		list_table.find('span>textarea[data-drunk]').each(function(i, e) {
            elem = $(e);
			span = elem.parent();
			panel = viewer.editor(elem, span);
			span.extenu(panel, 160);
			DC.init(panel);
        });
	},
	editor : function(elem, span){
		var ename = elem.attr('data-name'),
			eid = ename + Math.ceil(Math.random() * 1000000),
			eaction = elem.attr('data-action'),
			edrunk = elem.attr('data-drunk').replace("45,'{", "45,'{\\'container\\':\\'#" +eid+ "\\',"),
			evalue = elem.val(),
			form = $('<div class="panel_extenu"><textarea autocomplete="off" name="' +ename+ '" drunk="' +edrunk+ '">' +evalue+ '</textarea>'+
				'<span id="' +eid+ '"></span>'+
				'<div class="notice">&nbsp;</div>'+
				'<div class="control"><input type="button" class="button submit" value="保存" />'+
				'<input type="button" class="button cancel" value="取消" /></div></div>');

		var	notice = form.find('div.notice'),
			subutton = form.find('input.submit'),
			canbutton = form.find('input.cancel');

		subutton.bind('click', {'form':form,'span':span,'ename':ename,'action':eaction,'notice':notice}, viewer.save);
		canbutton.bind('click', {'span':span}, viewer.cancel);
		return form;
	},
	save : function(evt){
		var form = evt.data.form,
			vname = evt.data.ename,
			action = evt.data.action,
			notelem = evt.data.notice,
			value = form.find('[name='+vname+']').val(),
			data = {};
		data[vname] = value;
		$.post(action, data, function(json){
			if(!json)json = {'info':'操作失败，未知错误！','status':0};
			viewer.notice(notelem, !D.empty(json.status), json.info, function(){if(!D.empty(json.status))viewer.cancel(evt);});
		}, 'json');
	},
	notice : function(elem, bool, notice, callback){
		var color = ['#f00','#393'],
			timeout = 3000;
		elem.height('auto').html(notice);
		height = elem.height() ;
		elem.css('color', color[D.int(!!bool)]).height(0).hide();
		window.setTimeout(function(){elem.animate({'height':height + 'px','opacity':'show'}, 'fast', 'swing');}, 1) ;
		var autoHide = function(){elem.animate({'height':0,'opacity':'hide'}, 'slow', 'swing', callback);} ;
		if(timeout && timeout > 0)window.setTimeout(autoHide, timeout) ;
		return false ;
	},
	cancel : function(evt){
		evt.data.span.extenu(0,64);
	},
	search : function(){
		var form = $('form.search:first:not(.traditional)') ;
		if(!form.length)return ;
		var elems = form.find('[name]').not('[name^=__]') ,
			elem, ename, elem_parsed, vice_parament,
			main_elems = {} ,
			vice_elems = {} ,
			action = form.attr('action') ;
	
		elems.each(function(i, e){
			elem = $(e) ,
			ename = elem.attr('name') ;
			
			elem_parsed = ename.Split('-') ;
			vice_parament = ename.Split(':') ;
			
			if(elem_parsed.length > 1)main_elems[elem_parsed[1]] = [elem_parsed[0], elem_parsed[1], elem] ;
			if(vice_parament.length > 1)vice_elems[vice_parament[0]] = elem ;
		}) ;
		
		form.bind('submit', function(){
			var elem, k , type , vice,
				search_field = form.find('[name=field]'),
				search_keyword = form.find('[name=keyword]'),
				isfuzzy =  form.find('[name=fuzzy]').is(':checked'),
				config = [] ;
	
			for(k in main_elems){
				elem = main_elems[k][2] ;
				type = main_elems[k][0] ;
				vice = vice_elems[k] ? vice_elems[k].is(':checked') : false ;
				if(type == 'category'){
					config[config.length] = '1' + k + (vice ? '=' : '~*') + elem.val() ;
				}else if(type == 'status'){
					if(!D.empty(elem.val()))config[config.length] = '1' + k + '&' + elem.val() +','+ (vice ? 0 : elem.val()) ;
				}else if(type == 'selecter'){
					config[config.length] = '1' + k + '=' + elem.val() ;
				}else{
					config[config.length] = '1' + k + '=' + elem.val() ;
				}
			}
			if(search_keyword.val() !== '' && !DC.code(search_keyword, 1))config[config.length] = '7' + search_field.val() + (isfuzzy ? '~' : '=') + search_keyword.val() ;
			
			querys = config.join(';') ;
	
			location.href = action.replace(/!search/i, encodeURIComponent(querys).spechar(2)) ;
			return false ;
		}) ;
	}
};

var uclass = {
	expandStr : ['-', '+'], 
	event : function(){
		uclass.wrap = $('.unliclass');
		if(!uclass.wrap.length)return;
		uclass.wrap.find('i em').bind('click', function(){
			var e = $(this), bit = 0;
			uclass.expand(e, (e.text() == uclass.expandStr[0] ? 0 : 1) | bit);
		});
		uclass.wrap.find('>i>em').each(function(i, e){uclass.expand($(e), 1);});
		$('form.search').unbind('submit').bind('submit', uclass.search);
		$('form.search').find('input.expand_all').bind('click', function(){uclass.wrap.find('em:contains(+)').each(function(i, e){uclass.expand($(e), 1);});});
		$('form.search').find('input.shrink_all').bind('click', function(){uclass.wrap.find('em:contains(-)').each(function(i, e){uclass.expand($(e), 0);});});
	},
	expand : function(e, bit){
		var elem = e.parent(),
			celem = elem.next('b'),
			text ;
		if(bit & 1){
			e.text(uclass.expandStr[0]);
			celem.css('display', 'block');
		}else{
			e.text(uclass.expandStr[1]);
			celem.css('display', 'none');
		}
	},
	search : function(evt){
		var keywordsElem = $('input[name=keyword]'),
			keywords = keywordsElem.val() ;
		
		if(D.empty(keywords) || DC.code(keywordsElem, 1)){alert('请输入关键词！');return false;}
		uclass.wrap.find('em:contains(-)').each(function(i, e){uclass.expand($(e), 0);});
		uclass.wrap.find('span.highlight').removeClass('highlight');
		DC.keywords(uclass.wrap.find('i:contains('+keywords+')').each(function(i, e){
			var elem = $(e),
				em = elem.parent().prev('i').children('em'),
				p, i;
			do{
				uclass.expand(em, 1);
				p = em.parent().parent();
				i = p.prev('i');
				em = i.find('>em:first');
			}while(p.is('b') || p.is('div.unliclass'));
		}), keywords);
		return false;
	}
}

function pageMenuInit(){
	if(location.href.indexOf('engine') === -1)return ;
	$('.navigator>ul>li>a').bind('click', function(){$(this).parent().trigger('click'); /*return false;*/}).first().css('border-left', 0);
}

function developInit(){
	if(!/开发人员/.test(decodeURIComponent(D.cookie('member')) || ''))return;
	$('tr.field_develop').removeClass('field_develop');
}

$(function(){
	developInit();
	pageMenuInit();
	viewer.search();
	viewer.event();
	// version.check();
	uclass.event();
});

window.lele_version = version;
})();

function navCallback(i, tags, items, iscurrent){
	if(iscurrent){
		tags.eq(i).removeClass('act_next') ;
		var next = tags.eq(i + 1) ;
		if(!next.length)return false ;
		next.addClass('act_next')[0].mark = 1 ;
	}else{
		if(!tags[i].mark)return tags.eq(i).removeClass('act_next') ;
		tags[i].mark = 0 ;
	}
}

function navHoverCallback(i, items, method){
	var menu_items = $('.pl_wrap_in>div') ,
		menu_current = $('.menu_current') ;
	if(method === 'mouseover'){
		menu_current.append(menu_items.eq(i).children().clone()).show() ;
	}else{
		menu_current.empty().hide() ;
	}
}